<template>
    <div class="emotion-page">
        <h2 class="title1" style="margin-bottom: 20px;">
            <el-icon :size="25">
                <Reading />
            </el-icon> 用户情绪详情
        </h2>

        <!-- 上半部分：三个容器 -->
        <div class="top-section">
            <!-- 第一个容器：个人信息 -->
            <div class="personal-info-container">
                <div class="avatar">
                    <img :src="userInfo.avatarUrl || 'https://via.placeholder.com/100?text=头像'" alt="头像" />
                </div>
                <div class="user-name">{{ userInfo.name }}</div>
                <div class="user-birthday">生日：{{ userInfo.birthday }}</div>

                <div class="stats-section">
                    <div class="stat-item">
                        <div class="stat-icon">📊</div>
                        <div class="stat-content">
                            <div class="stat-number">{{ records.length }}</div>
                            <div class="stat-label">总检测数</div>
                        </div>
                    </div>

                    <div class="stat-item">
                        <div class="stat-icon">😊</div>
                        <div class="stat-content">
                            <div class="stat-number">{{ currentStatus }}</div>
                            <div class="stat-label">当前状态
                                <el-popover class="box-item" title="洛萨达比例" content="近7天的积极情绪与消极情绪的比值" width="150"
                                    placement="bottom">
                                    <template #reference>
                                        <el-icon size="12">
                                            <QuestionFilled />
                                        </el-icon>
                                    </template>
                                </el-popover>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第三个容器：图表分析 -->
            <div class="charts-container">
                <!-- <div class="chart-section1">
                    <h4>近五月情绪分析：</h4>
                    <div class="line-chart" ref="lineChartRef" style="width:100%;height:150px;"></div>
                </div> -->
                <div class="chart-section2">
                    <h4>最新情绪/近七天情绪记录：</h4>
                    <div class="radar-chart" ref="radarChartRef" style="width:100%;">
                    </div>
                </div>
            </div>
            <!-- 第二个容器：情绪热力图 -->
            <div class="emotion-heatmap-container">
                <div class="heatmap-title">情绪热力记录图</div>
                <div class="heatmap-grid">
                    <div v-for="(day, index) in heatmapData" :key="index" class="heatmap-cell-group">
                        <div class="heatmap-cell" :style="{ backgroundColor: getEmotionColor(day.emotion) }"
                            @mouseenter="showTooltip($event, day)" @mouseleave="hideTooltip"></div>
                        <!-- <div class="heatmap-label">{{ day.emotion }}</div> -->
                    </div>
                </div>

                <!-- 映射说明 -->
                <div class="emotion-legend">
                    <div class="legend-items">
                        <div v-for="emotion in emotions" :key="emotion.name" class="legend-item">
                            <div class="legend-color" :style="{ backgroundColor: emotion.color }"></div>
                            <span class="legend-text">{{ emotion.name }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 下半部分：情绪分析记录容器 -->
        <div class="bottom-section">
            <div class="analysis-records-container">
                <el-card class="box-card" shadow="never" style="width:100%;box-shadow:none;border:none;">
                    <template #header>
                        <div class="table-header">
                            <div class="card-header">
                                <span>情绪分析记录</span>
                            </div>
                        </div>
                    </template>
                    <el-table :data="displayedRecords" border style="width: 100%; margin-top: 20px;"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="60"></el-table-column>
                        <el-table-column label="序号" align="center" width="100">
                            <template #default="scope">
                                {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="id" label="记录ID" align="center" width="140"></el-table-column>
                        <el-table-column prop="uploadDate" label="上传时间" align="center"></el-table-column>
                        <el-table-column prop="image" label="上传图片" align="center" width="280">
                            <template #default="scope">
                                <div class="single-line-img">
                                    <span v-if="scope.row.image"
                                        style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-block;">
                                        {{ scope.row.image }}
                                    </span>
                                    <span v-else style="color:#bbb;">无</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="emotion_type" label="情绪类型" align="center">
                            <template #default="scope">
                                <el-tag :type="'info'" :style="{
                                    backgroundColor: emotions.find(e => e.name === emotionTranslations[scope.row.emotion_type])?.color || '#EBEDF0',
                                    color: '#333',
                                    border: 'none'
                                }" disable-transitions>
                                    {{ scope.row.emotion_type }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="350">
                            <template #default="scope">
                                <el-button type="primary" size="middle" @click="viewRecord(scope.row)">查看</el-button>
                                <el-button type="danger" size="middle" @click="deleteRecord(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- <div class="pagination-container" style="margin-top:20px;">
                        <el-pagination background layout="total, prev, pager, next" :total="filteredRecords.length"
                            :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" />
                    </div> -->

                    <!-- 分页 -->
                    <div class="pagination-container">
                        <el-pagination background layout="total, sizes, prev, pager, next"
                            :total="filteredRecords.length" :page-size="pageSize" :current-page="currentPage"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </el-card>



                <el-dialog v-model="dialogVisible" title="记录信息" width="900px" top="9vh" :close-on-click-modal="false"
                    center>
                    <div class="emo-detail-content2">
                        <!-- 第一行：记录ID和检测时间 -->
                        <div class="emo-row emo-row-top">
                            <div class="emo-col">
                                <span class="emo-detail-label">记录ID：</span>
                                <span class="emo-detail-value">{{ currentRecord?.id }}</span>
                            </div>
                            <div class="emo-col">
                                <span class="emo-detail-label">检测时间：</span>
                                <span class="emo-detail-value">{{ currentRecord?.uploadDate }}</span>
                            </div>
                        </div>
                        <!-- 第二行：上传图片和雷达图 -->
                        <div class="emo-row emo-row-img">
                            <div class="emo-col emo-img-col">
                                <span class="emo-detail-label">上传图片：</span>
                                <div class="emo-img-box2">
                                    <img v-if="currentRecord?.image" :src="currentRecord.image" alt="图片" />
                                </div>
                            </div>
                            <div class="emo-col emo-radar-col">
                                <span class="emo-detail-label">分析结果：</span>
                                <span class="emo-detail-value">
                                    <div ref="dialogRadarRef" style="width:320px;height:220px;"></div>
                                </span>

                            </div>
                        </div>
                        <!-- 第三行：情绪分析报告 -->
                        <div class="emo-detail-row emo-detail-report">
                            <div class="emo-detail-labe">情绪分析报告：</div>
                            <div class="emo-detail-value">

                                <!-- ...existing code... -->
                                <div v-if="dialogContentHtml" class="emo-rich-content" v-html="dialogContentHtml"></div>
                                <pre v-else class="emo-json">{{ formattedReport }}</pre>
                                <!-- ...existing code... -->
                            </div>
                        </div>
                    </div>
                    <div class="emo-detail-btn2">
                        <el-button type="primary" @click="dialogVisible = false">确认/关闭</el-button>
                        <el-button type="primary" @click="exportEmotionAnalyze">导出分析</el-button>
                    </div>
                </el-dialog>

                <!-- 悬停提示框 -->
                <div v-if="tooltip.show" class="tooltip" :style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }">
                    <div>{{ tooltip.emotion }}</div>
                    <div>{{ tooltip.date }}</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'
import MarkdownIt from 'markdown-it'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

const md = new MarkdownIt()
const router = useRouter()

// ================== 用户与页面状态 ==================
const userInfo = ref({
    userId: '',
    userName: '',
    avatarUrl: '',
    birthday: ''
})
const dialogVisible = ref(false)
const currentRecord = ref(null)
const formattedReport = ref('')
const records = ref([])
const currentStatus = ref('未知')

// ================== 统计与图表数据 ==================
const emotionTranslations = {
    'angry': '愤怒',
    'disgust': '厌恶',
    'surprise': '惊喜',
    'happy': '开心',
    'fear': '恐惧',
    'sad': '悲伤',
    'neutral': '中性',
    'unknown': '未检测'
}
const ratioData = [1.2, 0.8, 1.5, 2.0, 1.7]
const radarLabels = ['愤怒', '厌恶', '惊喜', '开心', '恐惧', '悲伤', '中性']
const radarData = [0, 0, 0, 0, 0, 0, 0]
const radarDataLatest = [0, 0, 0, 0, 0, 0, 0]

// ================== 热力图相关 ==================
const emotions = [
    { name: '愤怒', color: '#FF8899' },
    { name: '厌恶', color: '#E5EECF' },
    { name: '开心', color: '#FFEAC5' },
    { name: '恐惧', color: '#E5E1E8' },
    { name: '悲伤', color: '#C1D1E2' },
    { name: '惊喜', color: '#FFF2EA' },
    { name: '中性', color: '#EFFBD4' },
    { name: '未检测', color: '#EBEDF0' }
]
const heatmapData = ref([])
const tooltip = reactive({
    show: false,
    x: 0,
    y: 0,
    emotion: '',
    date: ''
})

// ================== 分页相关 ==================
const currentPage = ref(1)
const pageSize = ref(5)
const filteredRecords = computed(() => records.value)
const displayedRecords = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredRecords.value.slice(start, end)
})
const handleCurrentChange = (val) => { currentPage.value = val }
const handleSizeChange = (val) => { pageSize.value = val }

// ================== 图表实例相关 ==================
// const lineChartRef = ref(null)
// let chartInstance = null
const radarChartRef = ref(null)
let radarInstance = null

// 弹窗雷达图
const dialogRadarRef = ref(null)
let dialogRadarInstance = null

// ================== 初始化与生命周期 ==================
onMounted(() => {
    userInfo.value.userId = localStorage.getItem('userId')
    if (userInfo.value.userId) {
        fetchUser()
        fetchRecords()
    } else {
        ElNotification({
            title: '提示',
            message: '请通过“最新情绪”进入',
            type: 'error',
            duration: 3000
        })
        router.push('/user/latestEmotion')
    }
})

onBeforeUnmount(() => {
    // chartInstance && chartInstance.dispose()
    radarInstance && radarInstance.dispose()
    localStorage.removeItem('userId')
})

// ================== 业务方法 ==================

// 获取用户数据
const fetchUser = async () => {
    try {
        const response = await axios.get(`http://localhost:8181/user/getUser/${userInfo.value.userId}`, {
            headers: {
                [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue'),
            }
        })
        if (response.data.code === 200) {
            const data = response.data.data
            userInfo.value = {
                userId: data.userId,
                name: data.name,
                avatarUrl: data.avatarUrl,
                birthday: data.birthday ? data.birthday.slice(0, 10) : '未知'
            }
        } else {
            ElMessage.error(response.data.message || '获取用户信息失败')
        }
    } catch (error) {
        ElMessage.error('请求失败，请检查后端服务')
    }
}

// 获取记录数据（对接后端时只需修改此方法）
const fetchRecords = async () => {
    try {
        const response = await axios.get(`http://localhost:8181/uploadRecord/getRecordById/${userInfo.value.userId}`, {
            headers: {
                [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue'),
            }
        })
        if (response.data.code === 200) {
            records.value = response.data.data
                .map(item => ({
                    id: item.recordId,
                    image: item.fileUrl,
                    uploadTime: item.uploadTime || '',
                    uploadDate: item.uploadTime ? item.uploadTime.slice(0, 10) : '',
                    emotion_type: item.emotionType || '未检测',
                }))
                .sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime))
            ElMessage.success(`成功获取 ${records.value.length} 条记录`)
            generateHeatmapData()
            updateRadarData()
            await updateLatestRadarData()
            initCharts()
        } else {
            ElMessage.error(response.data.message || '获取记录失败')
        }
    } catch (error) {
        ElMessage.error('请求失败，请检查后端服务')
    }
}

// 新增：记录分析报告内容
const dialogContentHtml = ref('')

// 查看单条记录详情（对接后端分析报告）
const viewRecord = async (row) => {
    currentRecord.value = row
    formattedReport.value = '加载中...'
    dialogVisible.value = true
    dialogContentHtml.value = '' // 先清空

    try {
        const response = await axios.get(`http://localhost:8181/EmoAnalyze/getByRDId/${row.id}`)
        if (response.data.code === 200 && Array.isArray(response.data.data) && response.data.data.length > 0) {
            const report = response.data.data[0]
            currentRecord.value.emotionReport = {
                ...report,
                angry: report.angry,
                disgust: report.disgust,
                surprise: report.surprise,
                happy: report.happy,
                fear: report.fear,
                sad: report.sad,
                neutral: report.neutral
            }
            // 重点：用 markdown-it 渲染 analyze_content
            let content = report.analyze_content
            if (content && typeof content === 'string') {
                // 去除 <answer> 和 </answer>
                content = content.replace(/^<answer>\s*/i, '').replace(/\s*<\/answer>$/i, '')
                dialogContentHtml.value = md.render(content)
            } else {
                dialogContentHtml.value = ''
            }
            formattedReport.value = JSON.stringify(currentRecord.value.emotionReport, null, 2)
            await nextTick()
            renderDialogRadarChart()
        } else {
            dialogContentHtml.value = ''
            formattedReport.value = '暂无分析报告'
        }
    } catch (error) {
        dialogContentHtml.value = ''
        formattedReport.value = '获取分析报告失败'
        console.error(error)
    }
}

// 删除单条记录
const deleteRecord = async (row) => {
    try {
        await ElMessageBox.confirm(`确定要删除记录 ${row.id} 吗？`, '提示', { type: 'warning' })
        const response = await axios.delete(`http://localhost:8181/uploadRecord/delete/${row.id}`, {
            headers: {
                [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
            }
        })
        if (response.data.code === 200) {
            records.value = records.value.filter((r) => r.id !== row.id)
            ElMessage.success('删除成功')
            fetchRecords()
        } else {
            ElMessage.error(response.data.message || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('请求失败，请检查后端服务')
        }
    }
}

// 批量
const selectedRecords = ref([])
const handleSelectionChange = (val) => {
    selectedRecords.value = val
}

// 导出情绪分析报告为 PDF
const exportEmotionAnalyze = async () => {
    const name = userInfo.value.name || '用户'
    const date = currentRecord.value?.uploadDate || '未知日期'
    const fileName = `${name}_${date}.pdf`

    const element = document.querySelector('.emo-detail-content2')
    if (!element) {
        ElMessage.error('未找到导出内容区域')
        return
    }

    // 1. 找到分析内容容器
    const richContent = element.querySelector('.emo-rich-content')
    let oldStyle = ''
    if (richContent) {
        // 2. 记录原样式并移除max-height和overflow
        oldStyle = richContent.getAttribute('style') || ''
        richContent.style.maxHeight = 'none'
        richContent.style.overflow = 'visible'
    }

    // 3. 截图
    await nextTick() // 确保样式生效
    const canvas = await html2canvas(element, { scale: 2, useCORS: true })
    const imgData = canvas.toDataURL('image/jpeg', 1.0)

    // 4. 恢复原样式
    if (richContent) {
        richContent.setAttribute('style', oldStyle)
    }

    // 5. 生成PDF
    const pdf = new jsPDF('p', 'mm', 'a4')
    const pageWidth = pdf.internal.pageSize.getWidth()
    const imgWidth = pageWidth - 20
    const imgHeight = canvas.height * imgWidth / canvas.width

    pdf.addImage(imgData, 'JPEG', 10, 10, imgWidth, imgHeight)
    pdf.save(fileName)
}

// ================== 富文本处理 ==================
function formatAnalyzeContent(content) {
    if (!content) return ''
    // 替换<answer>为<div>，</answer>为</div>
    let html = content.replace(/^<answer>\s*/i, '').replace(/\s*<\/answer>$/i, '')
    // markdown转html
    return md.render(html)
}

// ================== 图表与热力图方法 ==================
function generateHeatmapData() {
    const data = []
    const today = new Date()
    for (let i = 27; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(today.getDate() - i)
        const dateStr = date.toISOString().slice(0, 10)
        const sameDayRecords = records.value
            .filter(r => r.uploadDate === dateStr)
        //.sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime))
        const record = sameDayRecords[0]
        data.push({
            date: formatDate(date),
            emotion: record ? (emotionTranslations[record.emotion_type] || record.emotion_type) : '未检测'
        })
    }
    heatmapData.value = data
}

function formatDate(date) {
    const year = date.getFullYear().toString().slice(-2)
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}${year}-${month}-${day}`
}

function getEmotionColor(emotion) {
    const emotionMap = emotions.find(e => e.name === emotion)
    return emotionMap ? emotionMap.color : '#EBEDF0'
}

function showTooltip(event, day) {
    tooltip.show = true
    tooltip.x = event.pageX + 10
    tooltip.y = event.pageY - 10
    tooltip.emotion = day.emotion
    tooltip.date = day.date
}

function hideTooltip() {
    tooltip.show = false
}

// 初始化主页面图表
function initCharts() {
    // 折线图
    // chartInstance = echarts.init(lineChartRef.value)
    // chartInstance.setOption({
    //     grid: { top: 10, bottom: 20, left: 40, right: 20 },
    //     tooltip: { trigger: 'axis' },
    //     xAxis: { type: 'category', data: months.value },
    //     yAxis: { type: 'value' },
    //     series: [{
    //         name: '积极/消极比值',
    //         type: 'line',
    //         data: ratioData,
    //         smooth: true,
    //         lineStyle: { color: '#4285f4', width: 3 },
    //         symbol: 'circle',
    //         itemStyle: { color: '#4285f4' }
    //     }]
    // })
    // 雷达图
    radarInstance = echarts.init(radarChartRef.value)

    radarInstance.setOption({
        grid: { top: -30, bottom: 20, left: 40, right: 20 },
        tooltip: {},
        legend: {
            data: ['近七天情绪分布', '最新情绪'],
            bottom: 10
        },
        radar: [
            {
                indicator: radarLabels.map(label => ({ name: label, max: Math.max(...radarData, 1) })),
                radius: '65%',
                center: ['50%', '44%'],
                splitNumber: 5,
                name: { textStyle: { fontSize: 12 } }
            },
            {
                indicator: radarLabels.map(label => ({ name: label, max: Math.max(...radarDataLatest, 0.01) })),
                radius: '65%',
                center: ['50%', '44%'],
                splitNumber: 5,
                name: { show: false }
            }
        ],
        series: [
            {
                type: 'radar',
                radarIndex: 0,
                name: '近七天情绪分布',
                data: [{ value: radarData, name: '近七天情绪分布' }],
                areaStyle: { color: 'rgba(66,133,244,0.15)' },
                lineStyle: { color: '#4285f4', width: 2 },
                symbol: 'circle',
                itemStyle: { color: '#4285f4', borderColor: '#4285f4', borderWidth: 2 }
            },
            {
                type: 'radar',
                radarIndex: 1,
                name: '最新情绪',
                data: [{ value: radarDataLatest, name: '最新情绪' }],
                areaStyle: { color: 'rgba(255,136,102,0.18)' },
                lineStyle: { color: '#ff8866', width: 2 },
                symbol: 'circle',
                itemStyle: { color: '#ffb48a', borderColor: '#ff8866', borderWidth: 2 }
            }
        ]
    })
}

// 弹窗雷达图渲染
function renderDialogRadarChart() {
    if (!dialogRadarRef.value) return
    if (!dialogRadarInstance) {
        dialogRadarInstance = echarts.init(dialogRadarRef.value)
    }
    const emo = currentRecord.value?.emotionReport || {}
    const data = [
        emo.angry ?? 0,
        emo.disgust ?? 0,
        emo.surprise ?? 0,
        emo.happy ?? 0,
        emo.fear ?? 0,
        emo.sad ?? 0,
        emo.neutral ?? 0
    ]
    dialogRadarInstance.setOption({
        tooltip: {},
        radar: {
            indicator: [
                { name: '愤怒', max: 1 },
                { name: '厌恶', max: 1 },
                { name: '惊喜', max: 1 },
                { name: '开心', max: 1 },
                { name: '恐惧', max: 1 },
                { name: '悲伤', max: 1 },
                { name: '中性', max: 1 }
            ],
            radius: '70%',
            name: { textStyle: { fontSize: 13 } }
        },
        series: [{
            type: 'radar',
            data: [{
                value: data,
                name: '情绪分布',
                areaStyle: { color: 'rgba(66,133,244,0.2)' },
                lineStyle: { color: '#4285f4', width: 2 },
                symbol: 'circle',
                itemStyle: { color: '#4285f4', borderColor: '#4285f4', borderWidth: 2 }
            }]
        }]
    })
}

// 弹窗关闭时销毁弹窗雷达图实例
watch(dialogVisible, (val) => {
    if (!val && dialogRadarInstance) {
        dialogRadarInstance.dispose()
        dialogRadarInstance = null
    }
})

const updateLatestRadarData = async () => {
    if (!records.value.length) return
    const latestRecord = records.value[0]
    if (!latestRecord || !latestRecord.id) return
    try {
        const response = await axios.get(`http://localhost:8181/EmoAnalyze/getByRDId/${latestRecord.id}`)
        if (response.data.code === 200 && Array.isArray(response.data.data) && response.data.data.length > 0) {
            const report = response.data.data[0]
            // 只提取情绪分值
            radarDataLatest.splice(0, radarDataLatest.length,
                report.angry ?? 0,
                report.disgust ?? 0,
                report.surprise ?? 0,
                report.happy ?? 0,
                report.fear ?? 0,
                report.sad ?? 0,
                report.neutral ?? 0
            )
            // 不需要处理其他内容
        }
    } catch (error) {
        // 可选：错误处理
        console.error('获取最新情绪分析失败', error)
    }
}

function updateRadarData() {
    // 近7天日期
    const today = new Date()
    const last7Days = []
    for (let i = 6; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(today.getDate() - i)
        last7Days.push(date.toISOString().slice(0, 10))
    }

    // 初始化情绪计数
    const emotionCount = {
        angry: 0,
        disgust: 0,
        surprise: 0,
        happy: 0,
        fear: 0,
        sad: 0,
        neutral: 0
    }

    // 统计近7天的情绪
    let positive = 0;
    let negative = 0;
    records.value.forEach(r => {
        if (last7Days.includes(r.uploadDate)) {
            const type = r.emotion_type
            if (emotionCount.hasOwnProperty(type)) {
                emotionCount[type]++
            }
            if (['happy', 'surprise', 'neutral'].includes(type)) positive++
            if (['angry', 'disgust', 'fear', 'sad'].includes(type)) negative++
        }
    })

    // 赋值给 radarData
    radarData.splice(0, radarData.length,
        emotionCount.angry,
        emotionCount.disgust,
        emotionCount.surprise,
        emotionCount.happy,
        emotionCount.fear,
        emotionCount.sad,
        emotionCount.neutral
    )

    // 计算比值，避免除0
    const ratio = negative === 0 ? positive : (positive / negative).toFixed(2)
    // 更新 ratioData，只保留一个值用于折线图
    ratioData.splice(0, ratioData.length, ratio)

    // 计算当前状态
    const numRatio = Number(ratio)
    if (isNaN(numRatio) || (positive === 0 && negative === 0)) {
        currentStatus.value = '未知'
    } else if (numRatio >= 0 && numRatio < 3) {
        currentStatus.value = '抑郁'
    } else if (numRatio >= 3 && numRatio < 4) {
        currentStatus.value = '疑似抑郁'
    } else if (numRatio >= 4 && numRatio < 9) {
        currentStatus.value = '正常'
    } else if (numRatio >= 9 && numRatio < 11) {
        currentStatus.value = '疑似过度乐观'
    } else if (numRatio >= 11) {
        currentStatus.value = '过度乐观'
    }
}
</script>

<style scoped>
.emotion-page {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    min-height: 100vh;
}

.title1 {
    display: flex;
    align-items: center;
    gap: 8px;
}

.top-section {
    display: flex;
    gap: 2.5%;
    justify-content: center;
    margin-bottom: 40px;
    flex-wrap: nowrap;
}

/* 第一个容器：个人信息 */
.personal-info-container {
    width: 380px;
    height: 380px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding: 20px 24px 0px 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 20px;
    border: 3px solid #e0e0e0;
}

.avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.user-name {
    font-size: 24px;
    font-weight: 700;
    color: #222;
    margin-bottom: 8px;
}

.user-birthday {
    font-size: 14px;
    color: #888;
    margin-bottom: 32px;
}

.stats-section {
    display: flex;
    gap: 64px;
    width: 100%;
    justify-content: center;
}

.stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.stat-icon {
    font-size: 28px;
    margin-bottom: 6px;
}

.stat-content {
    align-items: center;
    display: flex;
    flex-direction: column;
    flex: 1;
}

.stat-number {
    font-size: 20px;
    font-weight: 700;
    color: #4285f4;
}

.stat-label {
    font-size: 13px;
    color: #888;
}

/* 第二个容器：情绪热力图 */
.emotion-heatmap-container {
    width: 390px;
    height: 380px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding: 20px 24px 0px 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.heatmap-title {
    font-size: 22px;
    font-weight: 700;
    color: #222;
    text-align: center;
    margin-bottom: 24px;
}

.heatmap-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    grid-template-rows: repeat(4, 1fr);
    column-gap: 20px;
    row-gap: 20px;
    margin-bottom: 18px;
}

.heatmap-cell-group {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.heatmap-cell {
    width: 28px;
    height: 28px;
    border-radius: 6px;
    margin-bottom: 4px;
    transition: transform 0.2s;
    cursor: pointer;
    border: 1px solid #f0f0f0;
}

.heatmap-label {
    font-size: 12px;
    color: #888;
    text-align: center;
    margin-top: 2px;
    width: 32px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.emotion-legend {
    margin-top: 20px;
}

.legend-items {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    justify-content: center;
}

.legend-item {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: column;
    gap: 8px;
}

.legend-color {
    width: 16px;
    height: 16px;
    border-radius: 3px;
}

.legend-text {
    font-size: 12px;
    color: #666;
}

/* 第三个容器：图表 */
.charts-container {
    width: 460px;
    height: 400px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding: 0px 24px 0px 12px;
    flex-direction: column;
    align-items: center;
}

.chart-section1 {
    display: flex;
    flex-direction: column;
    height: 230px;
}

.chart-section2 {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.chart-section h4 {
    font-size: 16px;
    color: #222;
}

.line-chart {
    position: relative;
    width: 100%;
}

.chart-legend {
    display: flex;
    gap: 20px;
    justify-content: center;
    margin-top: 10px;
    font-size: 13px;
}

.legend-positive {
    color: #4285f4;
}

.legend-negative {
    color: #ff6b6b;
}

.radar-chart {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    /* 顶部对齐 */
    height: 100%;
}

/* 下半部分容器 */
.bottom-section {
    display: flex;
    justify-content: center;
    margin-bottom: 40px;
    flex-wrap: nowrap;
}

.analysis-records-container {
    width: 1471px;
    min-height: 200px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 30px;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    flex-direction: column;
}

.single-line-img {
    display: flex;
    align-items: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    height: 40px;
}

.emo-detail-content {
    width: 100%;
    padding: 10px 0 0 0;
    display: flex;
    flex-direction: column;
    align-items: stretch;
}

.emo-detail-content2 {
    width: 100%;
    padding: 10px 0 0 0;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    font-size: 16px;
}

.emo-row {
    display: flex;
    align-items: flex-start;
    margin-bottom: 28px;
}

.emo-row-top {
    display: flex;
    justify-content: flex-start;
    gap: 120px;
}

.emo-row-top .emo-col {
    display: flex;
    align-items: center;
    min-width: 260px;
}

.emo-detail-label {
    /* 固定宽度 */
    flex-shrink: 0;
    color: #333;
    font-weight: 500;
    text-align: left;
}

.emo-detail-value {
    flex: 1;
    min-width: 0;
    color: #222;
    margin-left: 6px;
}

.emo-row-img {
    gap: 40px;
}

.emo-img-col,
.emo-radar-col {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
}

.emo-img-box {
    background: #f5f5f5;
    border: 1px solid #eee;
    width: 200px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.emo-img-box2 {
    background: #f5f5f5;
    border: 1px solid #eee;
    width: 260px;
    height: 220px;
    /* 建议加上固定高度，便于图片充满 */
    display: flex;
    justify-content: center;
    align-items: center;
}

.emo-img-box img {
    max-width: 100%;
    max-height: 100%;
}

.emo-img-box2 img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.emo-radar-box {
    margin-top: 8px;
}

.emo-radar-placeholder {
    width: 260px;
    height: 220px;
    background: #f5f5f5;
    border: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: center;
}

.emo-detail-row {
    display: flex;
    align-items: flex-start;
    margin-bottom: 22px;
    font-size: 15px;
}

.emo-detail-report {
    align-items: flex-start;
}

.emo-json {
    font-family: "Consolas", "Menlo", "Monaco", monospace;
    font-size: 13px;
    background: #fafbfc;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    margin: 0;
    width: 700px;
    max-width: 700px;
    min-height: 300px;
    max-height: 380px;
    overflow: auto;
    white-space: pre-wrap;
    word-break: break-all;
}

.emo-rich-content {
    font-size: 14px;
    background: #fafbfc;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: auto;
    word-break: break-all;
    line-height: 1.7;
    width: 98%;
    min-height: 300px;
    max-height: 380px;
}

.emo-rich-content h3,
.emo-rich-content h4 {
    margin: 8px 0 4px 0;
    font-weight: bold;
}

.emo-rich-content ul,
.emo-rich-content ol {
    margin: 6px 0 6px 18px;
}

.emo-rich-content p {
    margin: 4px 0;
}

.emo-detail-btn {
    display: flex;
    justify-content: center;
    margin-top: 18px;
}

.pagination-container {
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
}

/* 提示框 */
.tooltip {
    position: absolute;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 12px;
    pointer-events: none;
    z-index: 1000;
    line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 1500px) {
    .top-section {
        flex-direction: column;
        align-items: center;
    }

    .analysis-records-container {
        width: 90%;
        max-width: 800px;
    }
}

@media (max-width: 768px) {

    .personal-info-container,
    .emotion-heatmap-container,
    .charts-container {
        width: 90%;
        max-width: 400px;
    }

    .stats-section {
        flex-direction: column;
        gap: 20px;
    }

    .heatmap-grid {
        max-width: 240px;
    }

    .heatmap-cell {
        width: 28px;
        height: 28px;
    }
}
.emo-detail-btn2{
    display: flex;
    justify-content: center;
    margin-top: 18px;
}
</style>